<template>
  <div id="app" style="width: 100%;height: 600px">
    <SpectrumView ref="spectrumViewRef"></SpectrumView>
    <input type="file" id="myFile" />
  </div>
</template>


<script lang="ts" setup>
import SpectrumView from './components/spectrum-view.vue'
import { useWebSocket } from '@vueuse/core';
import type { UseWebSocketReturn } from '@vueuse/core';

import { onMounted, onUnmounted, ref } from 'vue'

const spectrumViewRef = ref<any>(null);
const channelNumber = ref(1);
const wsUrl = 'ws://192.168.1.16:22202'
let wsConnection: UseWebSocketReturn<any> | null = null;
let start = performance.now();

// 处理 WebSocket 接收到的消息
const handleWebSocketMessage = async (_ws: WebSocket, event: MessageEvent) => {
  try {
    // 尝试将接收到的数据解析为 JSON 格式
    const data = JSON.parse(event.data);

    if (spectrumViewRef.value) {
      // const start = performance.now();
      spectrumViewRef.value.appendFftData(data.data,(data.frequnecy - data.bandwidth / 2) / 1e6,(data.frequnecy + data.bandwidth / 2) / 1e6);
      spectrumViewRef.value.setFreqRange({ left: (data.frequnecy - data.bandwidth / 2) / 1e6, right: (data.frequnecy + data.bandwidth / 2) / 1e6 });
      const end = performance.now();
      // console.log(`频谱数据更新时间间隔: ${end - start} ms,size: ${event.data.length/1024} KB`);
      start = performance.now();
    } else {
      // console.warn(`没有找到 SpectrumView`);
    }
  } catch (error) {
    console.error('Error parsing message:', error);
  }
};

onMounted(() => {
  wsConnection = useWebSocket(wsUrl, {
    autoReconnect: true,
    onMessage: handleWebSocketMessage,
    onError: (error: any) => {
      console.error('SenserChannel WebSocket error:', error);
    },
    onConnected: () => {
      console.info('SenserChannel WebSocket connected');
      wsConnection?.send(JSON.stringify({
        messageType: 'channelChange',
        channel: channelNumber.value,
      }));
    },
  });
})

onUnmounted(() => {
  // 在组件销毁前清除定时器
  wsConnection?.close();
});

</script>
<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #0b0e11;
  margin-top: 60px;
}
</style>
